package com.zabra.zl.ui.personal_center.presenter;

import com.zabra.zl.base.BasePresenter;
import com.zabra.zl.data.AccountBean;
import com.zabra.zl.data.SimpleBean;
import com.zabra.zl.net.RxScheduler;
import com.zabra.zl.ui.personal_center.contract.PersonalContract;
import com.zabra.zl.ui.personal_center.model.PersonalModel;

import io.reactivex.functions.Consumer;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PersonalPresenter extends BasePresenter<PersonalContract.View> implements PersonalContract.Presenter {
    private PersonalContract.Model model;

    public PersonalPresenter() {
        model=new PersonalModel();
    }

    @Override
    public void getData(RequestBody body) {
        if (!isViewAttached()) {
            return;
        }
        mView.showLoading();
        model.getData(body).compose(RxScheduler.Flo_io_main())
                .as(mView.bindAutoDispose())
                .subscribe(new Consumer<SimpleBean>() {
                    @Override
                    public void accept(SimpleBean bean) throws Exception {
                        mView.hideLoading();
                        mView.onSuccess(bean);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        mView.hideLoading();
                        mView.onError(throwable);
                    }
                });
    }

    @Override
    public void getUserData(RequestBody body) {
        if (!isViewAttached()) {
            return;
        }
        mView.showLoading();
        model.getUserData(body).enqueue(new Callback<AccountBean>() {
            @Override
            public void onResponse(Call<AccountBean> call, Response<AccountBean> response) {
                mView.hideLoading();
                mView.onSuccess(response.body(),response.headers().get("token"));
            }

            @Override
            public void onFailure(Call<AccountBean> call, Throwable t) {
                mView.hideLoading();
                mView.onError(t);
            }
        });
    }
}
